<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '创建作业',
  },
}
</route>

<script setup lang="ts">
import { reactive, ref, watch, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { FormExpose } from 'wot-design-uni/components/wd-form/types'
import dayjs from 'dayjs'
import { useToast } from 'wot-design-uni'
import api from '@/api'
import { useClassStore, useUserStore } from '@/store'

const userStore = useUserStore()
const classStore = useClassStore()

const toastApi = useToast()

const form = ref<FormExpose>()
const data = reactive<{
  model: {
    title: string
    description: string
    assignmentDate: number
    requirementType: 'audio' | 'read'
    classIds: number[]
    bookIds: number[]
  }
  selectableBooks: { value: number, label: string }[]
  createdClasses: { value: number, label: string }[]
  // 多班级支持
  classesData: Map<number, {
    classInfo: { id: number, name: string }
    members: Array<{
      userId: number
      nickname: string
      avatar: string | null
      role: string
      joinTime: string
      readingDays: number
      readingBooks: number
      todayPunched: boolean
    }>
    students: Array<{
      id: number
      nickname: string
      avatar: string | null
    }>
    selectedStudentIds: number[]
  }>
  currentClassId: number | null
  classMembers: Array<{
    userId: number
    nickname: string
    avatar: string | null
    role: string
    joinTime: string
    readingDays: number
    readingBooks: number
    todayPunched: boolean
  }>
  students: Array<{
    id: number
    nickname: string
    avatar: string | null
  }>
  // 绘本选择相关
  bookSets: Array<{
    id: number
    title: string
    cover: string
    bookCount: number
    description: string
  }>
  selectedBookSetId: number | null
  booksInSet: Array<{
    id: number
    title: string
    cover: string
    pages: number
  }>
  selectedBooks: Array<{
    id: number
    title: string
    cover: string
    bookSetTitle: string
  }>
  showBookSelector: boolean
  // 搜索相关
  bookSetSearchKeyword: string
  bookSearchKeyword: string
  filteredBookSets: Array<{
    id: number
    title: string
    cover: string
    bookCount: number
    description: string
  }>
  filteredBooks: Array<{
    id: number
    title: string
    cover: string
    pages: number
  }>
}>({
  model: {
    title: dayjs().format('MM月DD日作业'),
    description: dayjs().format('MM月DD日作业'),
    assignmentDate: Date.now(),
    requirementType: 'audio',
    classIds: [],
    bookIds: [],
  },
  selectableBooks: [],
  createdClasses: [],
  // 多班级支持
  classesData: new Map(),
  currentClassId: null,
  classMembers: [],
  students: [],
  bookSets: [],
  selectedBookSetId: null,
  booksInSet: [],
  selectedBooks: [],
  showBookSelector: false,
  bookSetSearchKeyword: '',
  bookSearchKeyword: '',
  filteredBookSets: [],
  filteredBooks: [],
})

// 获取当前班级的学生选择状态
function getCurrentClassStudents() {
  if (!data.currentClassId) return []
  const classData = data.classesData.get(data.currentClassId)
  // 如果多班级数据存在，使用多班级数据；否则回退到旧的单班级数据
  return classData?.students || data.students || []
}

function getCurrentClassSelectedIds() {
  if (!data.currentClassId) return []
  const classData = data.classesData.get(data.currentClassId)
  // 如果多班级数据存在，使用多班级数据；否则返回空数组（单班级模式下没有选中状态）
  return classData?.selectedStudentIds || []
}

// 计算属性：当前班级是否全选了所有学生
const isCurrentClassAllSelected = computed(() => {
  if (!data.currentClassId) return false
  const classData = data.classesData.get(data.currentClassId)
  if (!classData || classData.students.length === 0) return false

  return classData.students.every(student =>
    getStudentChecked(student.id)
  )
})

// 处理全选/取消全选当前班级学生
function handleSelectAllCurrentClassStudents() {
  if (!data.currentClassId) return
  const classData = data.classesData.get(data.currentClassId)
  if (!classData) return

  if (isCurrentClassAllSelected.value) {
    // 取消全选：对当前班级的每个学生调用取消选择
    classData.students.forEach(student => {
      setStudentChecked(student.id, false)
    })
  } else {
    // 全选：对当前班级的每个学生调用选择
    classData.students.forEach(student => {
      setStudentChecked(student.id, true)
    })
  }
}

// 获取学生选中状态（检查所有班级）
function getStudentChecked(studentId: number) {
  // 检查该学生是否在任何班级中被选中
  let isSelected = false
  data.classesData.forEach((classData) => {
    if (classData.selectedStudentIds.includes(studentId)) {
      isSelected = true
    }
  })
  return isSelected
}

// 设置学生选中状态（同步所有班级）
function setStudentChecked(studentId: number, event: any) {
  // 处理 wot-design-uni checkbox 的事件对象
  const isChecked = event === true || event?.detail?.value === true || event?.value === true

  // 同步更新所有包含该学生的班级
  data.classesData.forEach((classData) => {
    // 检查该班级是否包含这个学生
    const hasStudent = classData.students.some(student => student.id === studentId)
    if (!hasStudent) return

    if (isChecked) {
      // 添加到选中列表（如果还没有的话）
      if (!classData.selectedStudentIds.includes(studentId)) {
        classData.selectedStudentIds.push(studentId)
      }
    } else {
      // 从选中列表中移除
      const index = classData.selectedStudentIds.indexOf(studentId)
      if (index > -1) {
        classData.selectedStudentIds.splice(index, 1)
      }
    }
  })
}

// 获取所有班级选中的学生ID（去重）
function getAllSelectedStudentIds() {
  const allSelectedIds: number[] = []
  data.classesData.forEach((classData) => {
    allSelectedIds.push(...classData.selectedStudentIds)
  })
  // 使用Set去除重复的学生ID
  return Array.from(new Set(allSelectedIds))
}

// 获取所有班级选中的学生总数
function getTotalSelectedStudentsCount() {
  const selectedIds = getAllSelectedStudentIds()
  console.log('📊 选中的学生ID列表（已去重）:', selectedIds)
  return selectedIds.length
}

// 获取所有班级的学生总数（去重）
function getTotalStudentsCount() {
  const allStudentIds: number[] = []

  // 收集所有班级的学生ID
  data.classesData.forEach((classData) => {
    classData.students.forEach(student => {
      allStudentIds.push(student.id)
    })
  })

  // 如果没有多班级数据，回退到单班级模式的学生数量
  if (allStudentIds.length === 0 && data.students.length > 0) {
    return data.students.length
  }

  // 使用Set去除重复的学生ID，返回去重后的总数
  return Array.from(new Set(allStudentIds)).length
}

// 切换到指定班级
function switchToClass(classId: number) {
  data.currentClassId = classId
  const classData = data.classesData.get(classId)
  if (classData) {
    data.classMembers = classData.members
    data.students = classData.students
  }
}

// 获取班级显示名称
function getClassDisplayName(classId: number) {
  const classData = data.classesData.get(classId)
  return classData?.classInfo.name || `班级${classId}`
}

// 获取班级选中学生数量
function getClassSelectedCount(classId: number) {
  const classData = data.classesData.get(classId)
  return classData?.selectedStudentIds.length || 0
}

// 获取班级学生总数
function getClassStudentCount(classId: number) {
  const classData = data.classesData.get(classId)
  return classData?.students.length || 0
}



// 加载班级成员（支持多班级）
async function loadClassMembers(classId: number) {
  try {
    const { data: members } = await api.classes.getMembersByClassId(classId)

    // 获取班级信息
    const classInfo = data.createdClasses.find(c => c.value === classId)

    // 筛选出学生（排除老师）
    const students = members
      .filter(member => member.role !== 'teacher')
      .map(member => ({
        id: member.userId,
        nickname: member.nickname,
        avatar: member.avatar,
      }))

    // 存储到 classesData Map 中
    data.classesData.set(classId, {
      classInfo: { id: classId, name: classInfo?.label || `班级${classId}` },
      members: members,
      students: students,
      selectedStudentIds: []
    })

    // 如果是当前选中的班级，更新显示数据
    if (data.currentClassId === classId) {
      data.classMembers = members
      data.students = students
    }
  } catch (error) {
    toastApi.error('加载班级成员失败')
  }
}

// 监听班级选择变化（支持多班级）
async function handleClassChange() {
  // 验证用户是否为所有选中班级的创建者
  const invalidClasses = []
  for (const classId of data.model.classIds) {
    const classInfo = data.createdClasses.find(c => c.value === classId)
    if (!classInfo) {
      invalidClasses.push(classId)
    }
  }

  if (invalidClasses.length > 0) {
    toastApi.error('只能为自己创建的班级布置作业')
    // 移除无效的班级
    data.model.classIds = data.model.classIds.filter(id => !invalidClasses.includes(id))
    return
  }

  // 加载所有选中班级的成员
  for (const classId of data.model.classIds) {
    if (!data.classesData.has(classId)) {
      await loadClassMembers(classId)
    }
  }

  // 移除未选中班级的数据
  const classIdsToDelete = []
  data.classesData.forEach((_, classId) => {
    if (!data.model.classIds.includes(classId)) {
      classIdsToDelete.push(classId)
    }
  })
  classIdsToDelete.forEach(classId => data.classesData.delete(classId))

  // 设置当前显示的班级（第一个选中的班级）
  if (data.model.classIds.length > 0) {
    data.currentClassId = data.model.classIds[0]
    const classData = data.classesData.get(data.currentClassId)
    if (classData) {
      data.classMembers = classData.members
      data.students = classData.students
    }
  } else {
    data.currentClassId = null
    data.classMembers = []
    data.students = []
  }
}

// 使用watch监听班级选择变化
watch(() => data.model.classIds, async (newClassIds, oldClassIds) => {
  // 只有当班级ID真正发生变化时才处理
  if (JSON.stringify(newClassIds) !== JSON.stringify(oldClassIds)) {
    await handleClassChange()
  }
}, { immediate: false, deep: true })

// 加载绘本集列表
async function loadBookSets() {
  try {
    // 使用新的绘本集API
    const [chineseRes, englishRes] = await Promise.all([
      api.assignments.getSelectableBookSets('chinese'),
      api.assignments.getSelectableBookSets('english')
    ])

    // 检查API响应格式
    if (!chineseRes || !chineseRes.data || !englishRes || !englishRes.data) {
      toastApi.error('获取绘本集数据失败')
      return
    }

    // 检查数据是否为数组
    if (!Array.isArray(chineseRes.data) || !Array.isArray(englishRes.data)) {
      toastApi.error('绘本集数据格式错误')
      return
    }

    // 合并中英文绘本集
    const allBookSets = [...chineseRes.data, ...englishRes.data]

    // 转换为前端需要的格式
    data.bookSets = allBookSets.map(bookSet => ({
      id: bookSet.id,
      title: bookSet.title,
      cover: bookSet.cover || '',
      bookCount: bookSet.bookCount,
      description: bookSet.description || ''
    }))

    // 初始化过滤后的绘本集（显示所有）
    data.filteredBookSets = [...data.bookSets]

    if (data.bookSets.length === 0) {
      toastApi.warning('暂无可选绘本集')
    }

  } catch (error) {
    toastApi.error('加载绘本集失败: ' + (error.message || '网络错误'))
  }
}

// 打开绘本选择器
function openBookSelector() {
  data.showBookSelector = true
  // 每次打开都重新加载，确保数据最新
  loadBookSets()
}

// 关闭绘本选择器
function closeBookSelector() {
  data.showBookSelector = false
  data.selectedBookSetId = null
  data.booksInSet = []
}

// 选择绘本集
async function selectBookSet(value: any) {
  const bookSetId = Array.isArray(value) ? value[0] : value
  data.selectedBookSetId = bookSetId

  if (!bookSetId) {
    data.booksInSet = []
    return
  }

  try {
    console.log('开始加载绘本集内的绘本:', bookSetId)

    // 动态加载绘本集内的绘本
    const response = await api.assignments.getBooksByBookSetId(bookSetId)

    console.log('绘本集内绘本加载完成:', response)

    if (response && response.data && Array.isArray(response.data)) {
      data.booksInSet = response.data.map(book => ({
        id: book.id,
        title: book.title,
        cover: book.cover || '',
        pages: book.pages || 10
      }))

      // 初始化过滤后的绘本列表（显示所有）
      data.filteredBooks = [...data.booksInSet]

      const bookSet = data.bookSets.find(set => set.id === bookSetId)
      console.log('选择绘本集:', bookSet?.title, '包含绘本:', data.booksInSet.length)
    } else {
      console.error('绘本集内绘本数据格式错误:', response)
      data.booksInSet = []
      data.filteredBooks = []
      toastApi.error('加载绘本失败')
    }
  } catch (error) {
    console.error('加载绘本集内绘本失败:', error)
    data.booksInSet = []
    toastApi.error('加载绘本失败: ' + (error.message || '网络错误'))
  }
}

// 切换绘本选择状态
function toggleBookSelection(book: any) {
  const bookSetTitle = data.bookSets.find(set => set.id === data.selectedBookSetId)?.title || ''
  const bookIndex = data.selectedBooks.findIndex(b => b.id === book.id)

  if (bookIndex > -1) {
    // 取消选择
    data.selectedBooks.splice(bookIndex, 1)
  } else {
    // 添加选择
    data.selectedBooks.push({
      id: book.id,
      title: book.title,
      cover: book.cover,
      bookSetTitle
    })
  }

  // 更新model中的bookIds
  data.model.bookIds = data.selectedBooks.map(book => book.id)
}

// 确认选择
function confirmBookSelection() {
  if (data.selectedBooks.length === 0) {
    toastApi.error('请至少选择一本绘本')
    return
  }

  closeBookSelector()
  toastApi.success(`已选择 ${data.selectedBooks.length} 本绘本`)
}

// 移除已选择的绘本
function removeSelectedBook(bookId: number) {
  const index = data.selectedBooks.findIndex(book => book.id === bookId)
  if (index > -1) {
    data.selectedBooks.splice(index, 1)
    data.model.bookIds = data.selectedBooks.map(book => book.id)
  }
}

// 搜索绘本集
function searchBookSets() {
  const keyword = data.bookSetSearchKeyword.toLowerCase().trim()
  if (!keyword) {
    data.filteredBookSets = [...data.bookSets]
  } else {
    data.filteredBookSets = data.bookSets.filter(bookSet =>
      bookSet.title.toLowerCase().includes(keyword) ||
      bookSet.description.toLowerCase().includes(keyword)
    )
  }
}

// 搜索绘本
function searchBooks() {
  const keyword = data.bookSearchKeyword.toLowerCase().trim()
  if (!keyword) {
    data.filteredBooks = [...data.booksInSet]
  } else {
    data.filteredBooks = data.booksInSet.filter(book =>
      book.title.toLowerCase().includes(keyword)
    )
  }
}

// 清空绘本集搜索
function clearBookSetSearch() {
  data.bookSetSearchKeyword = ''
  data.filteredBookSets = [...data.bookSets]
}

// 清空绘本搜索
function clearBookSearch() {
  data.bookSearchKeyword = ''
  data.filteredBooks = [...data.booksInSet]
}

onLoad(async (query) => {
  const selectedClassId = query.classId as string
  const isMultiClassMode = query.multiClass === 'true'
  const defaultClassId = query.defaultClassId as string

  const { data: classes } = await api.classes.getClassesByCurrentUser()
  if (classes.length === 0) {
    await uni.navigateBack()
  }
  else {
    data.createdClasses = classes.filter(({ creatorId }) => `${creatorId}` === userStore.userInfo.id).map(({
      className,
      id,
    }) => ({
      value: id,
      label: className,
    }))

    // 处理班级选择
    if (isMultiClassMode) {
      // 多班级模式：设置默认班级并加载成员
      if (defaultClassId && data.createdClasses.find(({ value }) => `${value}` === defaultClassId)) {
        data.model.classIds = [Number.parseInt(defaultClassId)]
        data.currentClassId = Number.parseInt(defaultClassId)
        // 在多班级模式下也需要加载成员
        await loadClassMembers(Number.parseInt(defaultClassId))
      }
    } else if (selectedClassId) {
      // 单班级模式：自动加载班级成员
      if (data.createdClasses.find(({ value }) => `${value}` === selectedClassId) !== void 0) {
        data.model.classIds = [Number.parseInt(selectedClassId)]
        data.currentClassId = Number.parseInt(selectedClassId)
        // 加载选中班级的成员
        await loadClassMembers(Number.parseInt(selectedClassId))
      }
    }
  }

  // 初始化时加载绘本集数据
  loadBookSets()
})

const validators = {
  validateTitle: (title: string) => {
    if (title.trim().length > 0) {
      return Promise.resolve()
    }
    else {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('作业名称不可为空')
    }
  },
  validateDescription: (description: string) => {
    if (description.trim().length > 0) {
      return Promise.resolve()
    }
    else {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('作业描述不可为空')
    }
  },
  validateClass: (classes: object) => {
    if (Object.entries(classes).length > 0) {
      return Promise.resolve()
    }
    else {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('班级选择不可为空')
    }
  },
  validateBooks: () => {
    if (data.selectedBooks.length > 0) {
      return Promise.resolve()
    }
    else {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('请选择作业绘本')
    }
  },
}

async function handleSubmit() {
  const { valid, errors } = await form.value.validate()
  if (valid) {
    // 验证是否选择了班级
    if (data.model.classIds.length === 0) {
      toastApi.error('请至少选择一个班级')
      return
    }

    // 获取所有选中的学生
    const allSelectedStudentIds = getAllSelectedStudentIds()
    if (allSelectedStudentIds.length === 0) {
      toastApi.error('请至少选择一名学生参与作业')
      return
    }

    if (data.selectedBooks.length > 0) {
      try {
        // 调试信息：打印提交的数据
        const submitData = {
          classIds: data.model.classIds,
          bookIds: data.model.bookIds,
          assignmentDate: dayjs(data.model.assignmentDate).format('YYYY-MM-DD'),
          requirementType: data.model.requirementType,
          description: data.model.description,
          title: data.model.title,
          participantMemberIds: allSelectedStudentIds, // 所有选中的学生
        }
        console.log('📝 提交作业创建请求，数据:', submitData)

        // 使用多班级API创建作业
        const res = await api.assignments.createMultiClassAssignment(submitData)

        if (res.code === 0) {
          classStore.setInitialClassId(data.model.classIds[0])
          classStore.setRefresh(true)

          // 显示成功提示
          toastApi.success('作业创建成功！')

          // 延迟跳转，让用户看到成功提示
          setTimeout(() => {
            uni.navigateBack({
              delta: 1, // 返回上一页（班级页面）
            })
          }, 1000)
        } else {
          toastApi.error({
            msg: res.msg || '作业创建失败',
            duration: 1500,
          })
        }
      } catch (error) {
        console.error('创建作业失败:', error)
        toastApi.error({
          msg: '作业创建失败，请重试',
          duration: 1500,
        })
      }
    } else {
      toastApi.show({
        msg: '绘本选择不可为空',
        duration: 1500,
      })
    }
  }
  else {
    console.log(errors)
  }
}
</script>

<template>
  <view class="root-container">
    <wd-toast />
    <wd-card>
      <wd-form ref="form" :model="data.model" error-type="toast">
        <wd-cell-group>
          <wd-input
            v-model="data.model.title" label="作业名称：" label-width="80px" prop="title"
            placeholder="请输入作业名称……"
            :rules="[{ required: false, validator: validators.validateTitle, message: '' }]" clearable
          />
          <wd-input
            v-model="data.model.description" label="作业描述：" label-width="80px" prop="description"
            placeholder="请输入作业描述……"
            :rules="[{ required: false, validator: validators.validateDescription, message: '' }]" clearable
          />
          <wd-calendar
            v-model="data.model.assignmentDate" label="截止日期：" label-width="80px"
            prop="assignmentDate" placeholder="请选择截止日期……"
          />
          <wd-picker
            v-model="data.model.requirementType" label="完成条件：" label-width="80px" prop="requirementType"
            :columns="[{ label: `完成配音`, value: `audio` }, { label: `完成阅读`, value: `read` }]"
          />
          <wd-select-picker
            v-model="data.model.classIds" label="作业班级：" label-width="80px" prop="classIds"
            :columns="data.createdClasses" placeholder="请选择作业班级……"
            :rules="[{ required: false, validator: validators.validateClass, message: '' }]"
            @change="handleClassChange"
          />

          <!-- 多班级成员选择 -->
          <view v-if="data.model.classIds.length > 0" class="member-preview">
            <view class="preview-header">
              <wd-icon name="user-group" size="16px" color="#1890ff" />
              <text class="preview-title">选择参与作业的学生 (已选{{ getTotalSelectedStudentsCount() }}/{{ getTotalStudentsCount() }}人)</text>
            </view>

            <!-- 班级切换标签 -->
            <view v-if="data.model.classIds.length > 1" class="class-tabs">
              <view
                v-for="classId in data.model.classIds"
                :key="classId"
                class="class-tab"
                :class="{ active: data.currentClassId === classId }"
                @click="switchToClass(classId)"
              >
                <text class="tab-text">{{ getClassDisplayName(classId) }}</text>
                <text class="tab-count">({{ getClassSelectedCount(classId) }}/{{ getClassStudentCount(classId) }})</text>
              </view>
            </view>

            <!-- 当前班级的学生选择 -->
            <view v-if="data.currentClassId" class="current-class-students">
              <view class="class-header">
                <!-- <text class="class-name">{{ getClassDisplayName(data.currentClassId) }}</text> -->
                <wd-button
                  :type="isCurrentClassAllSelected ? 'warning' : 'primary'"
                  size="small"
                  plain
                  round
                  @click="handleSelectAllCurrentClassStudents"
                >
                  {{ isCurrentClassAllSelected ? '取消全选' : '全选' }}
                </wd-button>
              </view>

              <view v-if="getCurrentClassStudents().length > 0" class="student-container">
                <view class="student-list">
                  <view
                    v-for="student in getCurrentClassStudents()"
                    :key="student.id"
                    class="student-item"
                  >
                    <wd-checkbox
                      :model-value="getStudentChecked(student.id)"
                      @update:model-value="(checked: boolean) => setStudentChecked(student.id, checked)"
                    >
                      <view class="student-content">
                        <view class="student-avatar">
                          <wd-img
                            v-if="student.avatar"
                            :src="student.avatar"
                            width="32px"
                            height="32px"
                            shape="circle"
                          />
                          <view v-else class="avatar-placeholder">
                            {{ student.nickname.substring(0, 1) }}
                          </view>
                        </view>
                        <text class="student-name">{{ student.nickname }}</text>
                      </view>
                    </wd-checkbox>
                  </view>
                </view>
              </view>
            </view>

            <view v-else-if="data.currentClassId" class="no-students">
              <wd-icon name="warning" size="20px" color="#ff4d4f" />
              <text class="no-students-text">该班级没有学生，无法创建作业</text>
            </view>
          </view>
          <!-- 作业内容选择 -->
          <wd-cell
            title="作业内容："
            :value="data.selectedBooks.length > 0 ? `已选择 ${data.selectedBooks.length} 本绘本` : '请选择绘本'"
            clickable
            prop="bookIds"
            :rules="[{ required: false, validator: validators.validateBooks, message: '' }]"
            @click="openBookSelector"
          >
            <template #icon>
              <wd-icon name="book" size="16px" color="#1890ff" />
            </template>
            <template #value>
              <view class="book-selector-value">
                <text class="book-count" :class="{ placeholder: data.selectedBooks.length === 0 }">
                  {{ data.selectedBooks.length > 0 ? `${data.selectedBooks.length} 本绘本` : '请选择绘本' }}
                </text>
                <wd-icon name="arrow-right" size="16px" color="#999" />
              </view>
            </template>
          </wd-cell>

          <!-- 已选择的绘本预览 -->
          <view v-if="data.selectedBooks.length > 0" class="selected-books-preview">
            <view class="preview-header">
              <text class="preview-title">已选择的绘本 ({{ data.selectedBooks.length }}本)</text>
            </view>

            <!-- 横向滑动容器 -->
            <scroll-view
              class="books-scroll-horizontal"
              scroll-x
              :show-scrollbar="false"
              :enable-flex="true"
            >
              <view class="books-horizontal-list">
                <view
                  v-for="book in data.selectedBooks"
                  :key="book.id"
                  class="book-horizontal-item"
                >
                  <view class="book-cover-container">
                    <image
                      v-if="book.cover"
                      :src="book.cover"
                      class="book-cover-horizontal"
                      mode="aspectFill"
                    />
                    <view v-else class="cover-placeholder-horizontal">
                      {{ book.title.substring(0, 1) }}
                    </view>

                    <!-- 删除按钮 -->
                    <view
                      class="remove-btn"
                      @click="removeSelectedBook(book.id)"
                    >
                      <wd-icon name="close" size="12px" color="#fff" />
                    </view>
                  </view>

                  <view class="book-info-horizontal">
                    <text class="book-title-horizontal">{{ book.title }}</text>
                    <text class="book-set-horizontal">{{ book.bookSetTitle }}</text>
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
        </wd-cell-group>
        <view class="footer">
          <wd-button size="large" block custom-class="submit-btn" @click="handleSubmit">
            提交
          </wd-button>
        </view>
      </wd-form>
    </wd-card>

    <!-- 绘本选择器弹窗 -->
    <wd-popup
      v-model="data.showBookSelector"
      position="bottom"
      :safe-area-inset-bottom="true"
      custom-class="book-selector-popup"
    >
      <scroll-view
        class="book-selector-scroll"
        scroll-y
        :show-scrollbar="true"
      >
        <view class="book-selector">
          <view class="selector-header">
            <text class="selector-title">选择作业绘本</text>
            <wd-button
              type="text"
              icon="close"
              size="small"
              @click="closeBookSelector"
            />
          </view>

        <!-- 绘本集选择 -->
        <view class="book-set-section">
          <view class="section-title">
            <wd-icon name="folder" size="16px" color="#1890ff" />
            <text>第一步：选择绘本集 ({{ data.filteredBookSets.length }}/{{ data.bookSets.length }}个)</text>
          </view>

          <!-- 绘本集搜索框 -->
          <view v-if="data.bookSets.length > 0" class="search-container">
            <wd-search
              v-model="data.bookSetSearchKeyword"
              placeholder="搜索绘本集名称或描述..."
              @input="searchBookSets"
              @clear="clearBookSetSearch"
            />
          </view>

          <!-- 调试信息 -->
          <view v-if="data.bookSets.length === 0" class="debug-info">
            <text class="debug-text">正在加载绘本集数据...</text>
            <wd-button size="small" @click="loadBookSets">重新加载</wd-button>
          </view>

          <!-- 绘本集网格显示 -->
          <view v-if="data.filteredBookSets.length > 0" class="book-sets-grid">
            <view
              v-for="bookSet in data.filteredBookSets"
              :key="bookSet.id"
              class="book-set-item"
              :class="{ selected: data.selectedBookSetId === bookSet.id }"
              @click="selectBookSet(bookSet.id)"
            >
              <view class="book-set-cover">
                <image
                  v-if="bookSet.cover"
                  :src="bookSet.cover"
                  class="book-cover-grid"
                  mode="aspectFill"
                />
                <view v-else class="cover-placeholder">
                  {{ bookSet.title.substring(0, 1) }}
                </view>

                <!-- 绘本数量徽章 -->
                <view class="book-count-badge">{{ bookSet.bookCount }}本</view>

                <!-- 选中标识 -->
                <view
                  v-if="data.selectedBookSetId === bookSet.id"
                  class="selected-badge"
                >
                  <wd-icon name="check" size="14px" color="#fff" />
                </view>
              </view>

              <view class="book-set-info">
                <text class="book-set-title">{{ bookSet.title }}</text>
                <text v-if="bookSet.description" class="book-set-desc">{{ bookSet.description }}</text>
              </view>
            </view>
          </view>

          <!-- 无搜索结果 -->
          <view v-if="data.bookSets.length > 0 && data.filteredBookSets.length === 0" class="no-results">
            <wd-icon name="search" size="32px" color="#ccc" />
            <text class="no-results-text">未找到匹配的绘本集</text>
            <wd-button size="small" @click="clearBookSetSearch">清空搜索</wd-button>
          </view>
        </view>

        <!-- 绘本选择 -->
        <view v-if="data.selectedBookSetId && data.booksInSet.length > 0" class="books-section">
          <view class="section-title">
            <wd-icon name="books" size="16px" color="#1890ff" />
            <text>第二步：选择绘本 (已选{{ data.selectedBooks.length }}本，共{{ data.filteredBooks.length }}/{{ data.booksInSet.length }}本可选)</text>
          </view>

          <!-- 绘本搜索框 -->
          <view class="search-container">
            <wd-search
              v-model="data.bookSearchKeyword"
              placeholder="搜索绘本名称..."
              @input="searchBooks"
              @clear="clearBookSearch"
            />
          </view>

          <!-- 绘本网格显示 -->
          <view class="books-grid">
            <view
              v-for="book in data.filteredBooks"
              :key="book.id"
              class="book-grid-item"
              :class="{ selected: data.selectedBooks.some(b => b.id === book.id) }"
              @click="toggleBookSelection(book)"
            >
              <view class="book-cover-container">
                <image
                  v-if="book.cover"
                  :src="book.cover"
                  class="book-cover-grid"
                  mode="aspectFill"
                />
                <view v-else class="cover-placeholder">
                  {{ book.title.substring(0, 1) }}
                </view>

                <!-- 选中标识 -->
                <view
                  v-if="data.selectedBooks.some(b => b.id === book.id)"
                  class="selected-badge"
                >
                  <wd-icon name="check" size="12px" color="#fff" />
                </view>

                <!-- 绘本页数 -->
                <view class="book-pages">
                  {{ book.pages }}页
                </view>
              </view>

              <text class="book-title-grid">{{ book.title }}</text>
            </view>
          </view>

          <!-- 无搜索结果 -->
          <view v-if="data.booksInSet.length > 0 && data.filteredBooks.length === 0" class="no-results">
            <wd-icon name="search" size="32px" color="#ccc" />
            <text class="no-results-text">未找到匹配的绘本</text>
            <wd-button size="small" @click="clearBookSearch">清空搜索</wd-button>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-else-if="data.selectedBookSetId && data.booksInSet.length === 0" class="empty-state">
          <wd-icon name="warning" size="32px" color="#ccc" />
          <text class="empty-text">该绘本集暂无绘本</text>
        </view>

        <!-- 底部操作 -->
        <view class="selector-footer">
          <view class="selected-info">
            <text class="info-text">已选择 {{ data.selectedBooks.length }} 本绘本</text>
          </view>
          <wd-button
            size="large"
            custom-class="confirm-btn"
            :disabled="data.selectedBooks.length === 0"
            @click="confirmBookSelection"
          >
            确定选择
          </wd-button>
        </view>
      </view>
      </scroll-view>
    </wd-popup>
  </view>
</template>

<style scoped lang="scss">
// 导入公共样式变量
@import '@/styles/variables.scss';

.root-container {
  min-height: 95vh;
  padding: 15px 0;
  background: $bg-gradient;

  .footer {
    padding: 12px;
  }
}

// 成员预览样式
.member-preview {
  background: rgba(249, 250, 251, 0.8);
  border-radius: $border-radius-lg;
  padding: $spacing-lg;
  margin: $spacing-md 0;
  border: 1px solid rgba(229, 231, 235, 0.6);

  .preview-header {
    display: flex;
    align-items: center;
    gap: $spacing-sm;
    margin-bottom: $spacing-md;

    .preview-title {
      font-size: $font-size-base;
      color: $dark-gray;
      font-weight: $font-weight-semibold;
    }
  }

  // 班级切换标签样式
  .class-tabs {
    display: flex;
    gap: $spacing-sm;
    margin-bottom: $spacing-md;
    padding: 0 $spacing-xs;
    overflow-x: auto;

    .class-tab {
      flex-shrink: 0;
      padding: $spacing-xs $spacing-sm;
      border-radius: $border-radius-md;
      background: rgba(255, 255, 255, 0.8);
      border: 1px solid rgba(229, 231, 235, 0.8);
      cursor: pointer;
      transition: all 0.2s ease;

      &.active {
        background: $primary-blue;
        border-color: $primary-blue;
        color: white;

        .tab-text, .tab-count {
          color: white;
        }
      }

      &:hover:not(.active) {
        background: rgba(24, 144, 255, 0.1);
        border-color: rgba(24, 144, 255, 0.3);
      }

      .tab-text {
        font-size: $font-size-sm;
        font-weight: $font-weight-medium;
        color: $dark-gray;
      }

      .tab-count {
        font-size: $font-size-xs;
        color: $light-gray;
        margin-left: $spacing-xs;
      }
    }
  }

  .student-container {
    position: relative;

    .student-scroll {
      width: 100%;
      max-height: 180px; // 限制高度，大约显示3行学生
    }

    .student-list {
      display: flex;
      flex-direction: column;
      gap: $spacing-xs;
      padding: $spacing-xs 0;

      .student-item {
        flex-shrink: 0;
        width: 100%;
        margin-bottom: $spacing-sm;

        .student-content {
          display: flex;
          align-items: center;
          gap: $spacing-sm;
        }

        .student-avatar {
          .avatar-placeholder {
            @include center-flex;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: $blue-gradient;
            color: $white;
            font-size: $font-size-sm;
            font-weight: $font-weight-bold;
            box-shadow: 0 2px 4px rgba(83, 144, 245, 0.2);
          }
        }

        .student-name {
          font-size: $font-size-sm;
          color: $dark-gray;
          font-weight: $font-weight-medium;
          flex: 1;
        }
      }
    }

    .scroll-hint {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: $spacing-xs;
      margin-top: $spacing-sm;
      padding: $spacing-xs;
      background: rgba(153, 153, 153, 0.1);
      border-radius: $border-radius-md;

      .hint-text {
        font-size: $font-size-xs;
        color: #999;
        font-weight: $font-weight-medium;
      }
    }
  }

  .no-students {
    @include center-flex;
    flex-direction: column;
    gap: $spacing-sm;
    padding: $spacing-lg 0;

    .no-students-text {
      font-size: $font-size-sm;
      color: #ff4d4f;
      font-weight: $font-weight-medium;
      text-align: center;
    }
  }
}

// 自定义提交按钮样式
:deep(.submit-btn) {
  .wd-button {
    background: $blue-gradient;
    color: $white;
    border: none;
    border-radius: $border-radius-2xl;
    box-shadow: $shadow-blue;
    font-family: $font-family;
    font-size: $font-size-base;
    font-weight: $font-weight-semibold;
    transition: $transition-all;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 6px 16px rgba(66, 187, 255, 0.4);
    }

    &:active {
      transform: translateY(0);
      box-shadow: $shadow-blue;
    }

    &:disabled {
      background: linear-gradient(135deg, #cccccc 0%, #999999 100%);
      box-shadow: 0 2px 8px rgba(153, 153, 153, 0.2);
      transform: none;
    }
  }
}

// 绘本选择器样式
.book-selector-value {
  display: flex;
  align-items: center;
  // margin: 0 15px;
  gap: 8px;

  .book-count {
    font-size: 14px;
    color: #1890ff;
    font-weight: 500;

    &.placeholder {
      color: #999;
      font-weight: 400;
    }
  }
}

.selected-books-preview {
  background: rgba(249, 250, 251, 0.8);
  border-radius: $border-radius-lg;
  padding: $spacing-md;
  margin: $spacing-md 0;
  border: 1px solid rgba(229, 231, 235, 0.6);

  .preview-header {
    margin-bottom: $spacing-sm;

    .preview-title {
      font-size: $font-size-sm;
      color: $dark-gray;
      font-weight: $font-weight-semibold;
    }
  }

  // 横向滑动容器
  .books-scroll-horizontal {
    width: 100%;
    white-space: nowrap;
  }

  .books-horizontal-list {
    display: flex;
    gap: $spacing-md;
    padding: $spacing-xs 0;

    .book-horizontal-item {
      flex-shrink: 0;
      width: 80px;
      display: flex;
      flex-direction: column;
      align-items: center;

      .book-cover-container {
        position: relative;
        width: 60px;
        height: 80px;
        margin-bottom: $spacing-xs;

        .book-cover-horizontal {
          width: 100%;
          height: 100%;
          border-radius: $border-radius-md;
          background-color: $light-gray;
          box-shadow: $shadow-md;
        }

        .cover-placeholder-horizontal {
          @include center-flex;
          width: 100%;
          height: 100%;
          border-radius: $border-radius-md;
          background: $blue-gradient;
          color: $white;
          font-size: $font-size-lg;
          font-weight: $font-weight-bold;
          box-shadow: $shadow-md;
        }

        .remove-btn {
          position: absolute;
          top: -6px;
          right: -6px;
          @include center-flex;
          width: 20px;
          height: 20px;
          border-radius: 50%;
          background: #ff4d4f;
          border: 2px solid $white;
          box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
          cursor: pointer;
          transition: $transition-all;

          &:active {
            transform: scale(0.9);
          }
        }
      }

      .book-info-horizontal {
        width: 100%;
        text-align: center;

        .book-title-horizontal {
          font-size: $font-size-xs;
          color: $dark-gray;
          font-weight: $font-weight-semibold;
          line-height: 1.2;
          margin-bottom: 2px;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          height: 24px; // 预留两行高度
        }

        .book-set-horizontal {
          font-size: $font-size-xs;
          color: $medium-gray;
          font-weight: $font-weight-regular;
          line-height: 1.2;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
}

// 新增的绘本集选择列表样式
.selected-booksets-container {
  padding: 10px 15px; // 与 wd-cell-group 内部的 padding 保持一致
  background-color: #fff; // 与 wd-cell-group 背景色一致
  border-top: 1px solid #f2f2f2; // 模拟 wd-cell 的分割线

  .bookset-item {
    display: flex;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f7f7f7; // 每个绘本集项之间的分割线
    &:last-child {
      border-bottom: none; // 最后一个不显示下边线
    }

    .bookset-cover {
      width: 48px; // 调整尺寸使其更适合作业页面
      height: 48px;
      border-radius: 6px;
      margin-right: 12px;
      background-color: #e9ecef;
      flex-shrink: 0; // 防止图片被压缩
    }

    .bookset-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      min-width: 0; // 允许文本溢出隐藏

      .bookset-title {
        font-size: 15px;
        color: #333;
        font-weight: 500;
        white-space: nowrap; // 标题不换行
        overflow: hidden; // 溢出隐藏
        text-overflow: ellipsis; // 溢出显示省略号
      }

      .bookset-count {
        font-size: 12px;
        color: #999;
        margin-top: 2px;
      }
    }

    .remove-icon {
      color: #999;
      margin-left: 10px;
      // 可选：增加点击区域
      padding: 5px;
      // 为了让点击更方便，可以增加伪元素
      position: relative;

      &::after {
        content: '';
        position: absolute;
        top: -5px;
        left: -5px;
        right: -5px;
        bottom: -5px;
        // background: rgba(0,0,0,0.1); // 用于调试点击区域
      }
    }
  }
}

// 弹窗滚动容器
.book-selector-scroll {
  max-height: 85vh;
  min-height: 65vh; // 确保能显示三行绘本集
  height: 70vh; // 默认高度，显示三行绘本集
  background: $white;
  border-radius: $border-radius-xl $border-radius-xl 0 0;
}

.book-selector {
  background: $white;
  min-height: 100%;
  display: flex;
  flex-direction: column;
  padding-bottom: $spacing-lg; // 确保底部有足够空间
  margin: 0 15px;

  .selector-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: $spacing-lg;
    border-bottom: 1px solid $border-color-light;

    .selector-title {
      font-size: $font-size-xl;
      font-weight: $font-weight-bold;
      color: $dark-gray;
    }
  }

  .book-set-section {
    padding: $spacing-lg;
    border-bottom: 1px solid rgba(229, 231, 235, 0.3);

    .section-title {
      display: flex;
      align-items: center;
      gap: $spacing-sm;
      margin-bottom: $spacing-md;

      text {
        font-size: $font-size-base;
        color: $dark-gray;
        font-weight: $font-weight-semibold;
      }
    }

    .search-container {
      margin-bottom: $spacing-md;
    }

    .book-sets-grid {
      display: flex;
      flex-wrap: wrap;
      justify-content: left;
      gap: $spacing-md;
      padding: $spacing-sm 0;

      .book-set-item {
        width: 30%; // 每行显示3个，与首页保持一致
        margin-bottom: $spacing-xl;
        display: flex;
        flex-direction: column;
        cursor: pointer;
        transition: $transition-all;

        &:active {
          transform: scale(0.95);
        }

        &:hover {
          transform: translateY(-4px);
        }

        &.selected {
          .book-set-cover {
            .book-cover-grid, .cover-placeholder {
              box-shadow: 0 8px 24px rgba(24, 144, 255, 0.3);
              border: 3px solid #1890ff;
            }
          }
        }

        .book-set-cover {
          position: relative;
          width: 100%;

          .book-cover-grid {
            width: 100%;
            height: 120px; // 统一高度
            border-radius: $border-radius-lg;
            background-color: $light-gray;
            box-shadow: $shadow-lg;
            transition: $transition-all;
          }

          .cover-placeholder {
            @include center-flex;
            width: 100%;
            height: 120px; // 与图片相同高度
            border-radius: $border-radius-lg;
            background: $blue-gradient;
            color: $white;
            font-size: $font-size-xl;
            font-weight: $font-weight-bold;
            box-shadow: $shadow-lg;
            transition: $transition-all;
          }

          .selected-badge {
            position: absolute;
            top: $spacing-sm;
            right: $spacing-sm;
            @include center-flex;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background: #52c41a;
            border: 2px solid $white;
            box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
          }

          .book-count-badge {
            position: absolute;
            top: $spacing-sm;
            left: $spacing-sm;
            background: $yellow-gradient;
            color: $white;
            padding: 2px 6px;
            border-radius: $border-radius-sm;
            font-size: $font-size-xs;
            font-weight: $font-weight-bold;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
          }
        }

        .book-set-info {
          padding: $spacing-sm 0;

          .book-set-title {
            font-size: $font-size-sm;
            color: $dark-gray;
            font-weight: $font-weight-bold;
            line-height: 1.3;
            margin-bottom: $spacing-xs;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .book-set-desc {
            font-size: $font-size-xs;
            color: $medium-gray;
            font-weight: $font-weight-regular;
            line-height: 1.2;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }

  .books-section {
    padding: $spacing-lg;

    .section-title {
      display: flex;
      align-items: center;
      gap: $spacing-sm;
      margin-bottom: $spacing-md;

      text {
        font-size: $font-size-base;
        color: $dark-gray;
        font-weight: $font-weight-semibold;
      }
    }

    .search-container {
      margin-bottom: $spacing-md;
    }

    .books-grid {
      display: flex;
      flex-wrap: wrap;
      justify-content: left;
      gap: $spacing-md;
      padding: $spacing-sm 0;

      .book-grid-item {
        width: 30%; // 每行显示3个，与绘本集详情页保持一致
        display: flex;
        flex-direction: column;
        cursor: pointer;
        transition: $transition-all;

        &:active {
          transform: scale(0.95);
        }

        &.selected {
          .book-cover-container {
            .book-cover-grid, .cover-placeholder {
              box-shadow: 0 8px 24px rgba(24, 144, 255, 0.3);
              border: 3px solid #1890ff;
            }
          }
        }

        .book-cover-container {
          position: relative;
          width: 100%;
          margin-bottom: $spacing-sm;

          .book-cover-grid {
            width: 100%;
            height: 120px; // 使用统一的绘本封面高度
            border-radius: $border-radius-lg;
            background-color: $light-gray;
            box-shadow: $shadow-lg;
            transition: $transition-all;
          }

          .cover-placeholder {
            @include center-flex;
            width: 100%;
            height: 120px; // 与图片相同高度
            border-radius: $border-radius-lg;
            background: $blue-gradient;
            color: $white;
            font-size: $font-size-xl;
            font-weight: $font-weight-bold;
            box-shadow: $shadow-lg;
            transition: $transition-all;
          }

          // 选中状态徽章
          .selected-badge {
            position: absolute;
            top: $spacing-sm;
            left: $spacing-sm;
            @include center-flex;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background: #52c41a;
            border: 2px solid $white;
            box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
          }

          // 绘本页数
          .book-pages {
            position: absolute;
            bottom: $spacing-sm;
            right: $spacing-sm;
            background-color: rgba(0, 0, 0, 0.5);
            color: $white;
            font-size: $font-size-sm;
            font-family: $font-family;
            padding: $spacing-xs $spacing-sm;
            border-radius: $border-radius-sm;
          }
        }

        .book-title-grid {
          font-size: $font-size-base;
          color: $dark-gray;
          font-weight: $font-weight-medium;
          font-family: $font-family;
          text-align: center;
          line-height: 1.3;
          // 最多显示两行
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          height: 36px; // 预留两行的高度
        }
      }
    }
  }

  .debug-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: $spacing-md;
    background: rgba(255, 193, 7, 0.1);
    border-radius: $border-radius-md;
    margin-bottom: $spacing-md;

    .debug-text {
      font-size: $font-size-sm;
      color: #856404;
      font-weight: $font-weight-medium;
    }
  }

  .empty-state {
    @include center-flex;
    flex-direction: column;
    gap: $spacing-md;
    padding: $spacing-2xl;

    .empty-text {
      font-size: $font-size-sm;
      color: $medium-gray;
      font-weight: $font-weight-medium;
    }
  }

  .no-results {
    @include center-flex;
    flex-direction: column;
    gap: $spacing-md;
    padding: $spacing-2xl;

    .no-results-text {
      font-size: $font-size-sm;
      color: $medium-gray;
      font-weight: $font-weight-medium;
      text-align: center;
    }
  }

  .selector-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: $spacing-lg;
    border-top: 1px solid $border-color-light;

    .selected-info {
      .info-text {
        font-size: $font-size-sm;
        color: $medium-gray;
        font-weight: $font-weight-medium;
      }
    }
  }



  // 当前班级学生选择样式
  .current-class-students {
    .class-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;

      .class-name {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }

      // 全选按钮样式
      :deep(.wd-button) {
        min-width: 60px;
        height: 28px;
        font-size: 12px;

        &.wd-button--primary {
          background: linear-gradient(135deg, #1890ff, #40a9ff);
          border-color: #1890ff;

          &.wd-button--plain {
            background: transparent;
            color: #1890ff;
            border-color: #1890ff;
          }
        }

        &.wd-button--warning {
          background: linear-gradient(135deg, #fa8c16, #ffa940);
          border-color: #fa8c16;

          &.wd-button--plain {
            background: transparent;
            color: #fa8c16;
            border-color: #fa8c16;
          }
        }
      }
    }
  }


}

</style>
